/**
 * 扁平数据结构转Tree
 */

let arr = [
  { id: 1, name: "部门1", pid: 0 },
  { id: 2, name: "部门2", pid: 1 },
  { id: 3, name: "部门3", pid: 1 },
  { id: 4, name: "部门4", pid: 3 },
  { id: 5, name: "部门5", pid: 4 },
  { id: 7, name: "部门7", pid: 6 },
];
// 输出结果
const result = [
  {
    id: 1,
    name: "部门1",
    pid: 0,
    children: [
      {
        id: 2,
        name: "部门2",
        pid: 1,
        children: [],
      },
      {
        id: 3,
        name: "部门3",
        pid: 1,
        children: [
          // 结果 ,,,
        ],
      },
    ],
  },
];

/**
 * 方法一：递归法
 */
function recursionArrToTree(pid, list) {
  return list
    .filter((item) => item.pid === pid)
    .map((item) => ({ ...item, children: recursionArrToTree(item.id, list) }));
}

/**
 * 性能最优法
 */
function arrayToTree(list) {
  const result = [];
  const map = new Map();
  list.forEach((node) => {
    map.set(node.id, { ...node, children: [] });
  });

  list.forEach((node) => {
    const cid = map.get(node.id);
    const pid = map.get(node.pid);

    if (pid) {
      pid.children.push(cid);
    } else {
      result.push(cid);
    }
  });
  return result;
}
console.log(arrayToTree(arr));
